package com.njworkorder.Service.Impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.njworkorder.Annotation.CustomCache;
import com.njworkorder.Service.VideoPlatformService;
import com.njworkorder.Utils.WebClientUtil;
import com.njworkorder.VO.VideoPlatformVo.VideoPlatVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Service
public class VideoPlatformServiceImpl implements VideoPlatformService {

    @Value("${video_platform.key}")
    private String key;
    @Value("${video_platform.secret}")
    private String secret;
    @Value("${video_platform.getAccessTokenUrl}")
    private String getAccessTokenUrl;
    @Value("${video_platform.getVideoPage}")
    private String getVideoPageUrl;
    @Value("${video_platform.getCameraPlayURL}")
    private String getCameraPlayURL;

    private final long expireTime = 1440;

    @CustomCache(cacheNames = "token",key = "#accessToken",ttl = expireTime)
    @Override
    public VideoPlatVo getAccessToken(String accessToken) {
        Map<String, String> params = new HashMap<>();
        params.put("key", key);
        params.put("secret", secret);

        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");

        return WebClientUtil.post(getAccessTokenUrl, params, header, VideoPlatVo.class).block();
    }

    @Override
    public Mono<VideoPlatVo> getVideoPage(String currPage,String pageSize) {
        Map<String, String> params = new HashMap<>();
        params.put("currPage", currPage);
        params.put("pageSize", pageSize);

        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        header.put("Authorization", getToken());

        return WebClientUtil.get(getVideoPageUrl, params, header, VideoPlatVo.class);
    }

    @Override
    public Mono<VideoPlatVo> getCameraPlayURL(String id,String videoFormat,String videoRate) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id);
        params.put("videoFormat", videoFormat);
        params.put("videoRate", videoRate);

        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        header.put("Authorization", getToken());

        return WebClientUtil.get(getCameraPlayURL, params, header, VideoPlatVo.class);
    }


    private String getToken() {
        VideoPlatVo accessToken = getAccessToken("accessToken");
        Object data = accessToken.getData();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.valueToTree(data);
        return jsonNode.get("accessToken").asText();
    }

}
